#include "getthread.h"


GetThread::GetThread(QObject *parent) : QThread(parent)
{
    nam = new QNetworkAccessManager(this);
}
GetThread::~GetThread(){

}

void GetThread::getEos(){
    QUrl url("http://api.zb.com/data/v1/ticker?market=eos_qc");
    QNetworkReply* reply = nam->get ( QNetworkRequest(url));
    setValue (reply,true);

}

void GetThread::getEpc(){
    QUrl url("http://api.zb.com/data/v1/ticker?market=epc_qc");
    QNetworkReply* reply = nam->get ( QNetworkRequest(url));
    setValue (reply,false);
}
void GetThread::run(){
    while (true) {
        getEos();
        getEpc();
        sleep(1000);
    }
}

void GetThread::setValue (QNetworkReply *reply, bool eos)
{
    QVariant redirectionTargetUrl =
         reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if(reply->error () == QNetworkReply::NoError){
        QByteArray bytes = reply->readAll ();
        QString json = QString::fromUtf8 (bytes);
        QJsonParseError jsonError;
        QJsonDocument document = QJsonDocument::fromJson(bytes,&jsonError);
        if(!document.isNull() && jsonError.error == QJsonParseError::NoError){
            if(document.isObject()){
                QJsonObject object = document.object();
                if(object.contains("ticker")){
                    QJsonValue o = object.value("ticker");
                    QJsonObject ticker = o.toObject();
                    QString last = ticker.value("last").toString();    //最新成交价
                    qDebug() << "最新成交价" << last;
                    emit UpdateSignal(last,eos);
                }
            }
        }

    }
}
